# -*- coding: utf-8 -*-.
'''阿里云短信服务模板

sign_name: 湖北三沃力源航天科技
template_code: 
    UR气囊上限预警通知短信: SMS_213690733  您的亲属(${name})设备气囊触发次数已达到上限,为确保设备安全工作请及时更换！
    LA疑似跌倒模板: SMS_213740726 您的亲属(${name})在${address}附近疑似跌倒,请您及时确认并前往救助！
    UR跌倒模板: SMS_213690724 您的亲属(${name})在${address}附近跌倒,请您及时确认并前往救助！
'''
import json
from typing import List
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

from settings import *
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)
class SendSms:
    def __init__(self, phone_numbers="18000305696", sign_name='安护宁', template_code='SMS_208642031', template_param={}):
        self.sign_name = sign_name
        self.template_code = template_code
        self.phone_numbers = phone_numbers
        self.template_param = template_param

    @staticmethod
    def create_client() -> Dysmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        # 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id=ALIBABA_CLOUD_ACCESS_KEY_ID,
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret=ALIBABA_CLOUD_ACCESS_KEY_SECRET
        )
        # Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(config)

    def main(self) -> str:
        client = self.create_client()
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name=self.sign_name,
            template_code=self.template_code,
            phone_numbers=self.phone_numbers,
            template_param=json.dumps(self.template_param)
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            response = client.send_sms_with_options(send_sms_request, runtime)

        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            # print(error.message)
            # 诊断地址
            # print(error.data.get("Recommend"))
            logger.error("短信发送失败：")
            logger.error(error.message)
            UtilClient.assert_as_string(error.message)
            return error.message

        else:
            logger.info("短信发送返回值：")
            logger.info(response.to_map())

            return response.to_map().get("body").get("Message")

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = SendSms.create_client()
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name='阿里云短信测试',
            template_code='SMS_154950909',
            phone_numbers='18000305696',
            template_param='{"code":"1234"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            await client.send_sms_with_options_async(send_sms_request, runtime)
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

if __name__ == '__main__':
    SendSms().main()
